const cloud = require('wx-server-sdk')
cloud.init({
  // API 调用都保持和云函数当前所在环境一致
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database()
const MAX_LIMIT = 100;

const _ = db.command;
exports.main = async (event, context) => {
  let category_id = event.category_id;
  let condition = {};
  if(category_id){
    condition.category_id = category_id
  }
  condition._id = _.nin(['b00064a7606ebdf00dabf6960b4977b8', '79550af2606ec0950dc0100c50f497da']);
  // 先取出集合记录总数
  const countResult = await db.collection('books').where(condition).count();
  const total = countResult.total;
  if(total == 0){
    return {
      data: [],
      errMsg: null
    }
  }
  // 计算需分几次取
  const batchTimes = Math.ceil(total / 100)
  // 承载所有读操作的 promise 的数组
  const tasks = []
  for (let i = 0; i < batchTimes; i++) {
    const promise = db.collection('books').where(condition).skip(i * MAX_LIMIT).limit(MAX_LIMIT).orderBy('sort', 'asc').get()
    tasks.push(promise)
  }
  // 等待所有
  return (await Promise.all(tasks)).reduce((acc, cur) => {
    return {
      data: acc.data.concat(cur.data),
      errMsg: acc.errMsg,
    }
  })
}